package com.engine.jucailinkq.attendance.workflow.action;

import com.engine.jucailinkq.attendance.enums.AccountingUnitEnum;
import com.engine.jucailinkq.attendance.workflow.service.MakeUpClockInService;
import com.engine.jucailinkq.attendance.workflow.service.impl.MakeUpClockInServiceImpl;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.common.util.ServiceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Cell;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 撤销出差
 */
@Slf4j
public class RevokeEliminationsAskForLeaveAction implements Action {

    private MakeUpClockInService makeUpClockInService = ServiceUtil.getService(MakeUpClockInServiceImpl.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        log.debug("RevokeEliminationsAskForLeaveAction,do action on request:" + requestInfo.getRequestid());
        String requestid = requestInfo.getRequestid();
        try {

            // 流程表单主表数据
            HashMap<String, String> mainTableData = CommonUtil.getMainTableInfo(requestInfo);
            String qjlx = mainTableData.get("qjlx");
            String xjr = mainTableData.get("xjr");

            String queryItemsql = "select hsdw,hsl from uf_jcl_kq_kqxm  where id=?";
            Map<String, Object> holidayItem = DbTools.getSqlToMap(queryItemsql, qjlx);

            DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();
            log.debug("RevokeLeaveAction detailTable : [{}], length : {}", Arrays.toString(detailTable), detailTable.length);
            List<Map<String, String>> updateList = new ArrayList<>();
            //记录需要更改出勤结果数据状态的人员、日期信息
            List<Map<String, String>> empDateList = new ArrayList<>();
            Map<String, String> empDateItem;
            List<String> dateList = new ArrayList<>();
            if (detailTable.length > 0) {
                for (DetailTable dt : detailTable) {
                    //明细表
                    Row[] s = dt.getRow();
                    for (Row r : s) {
                        //行
                        Cell[] h = r.getCell();
                        Map<String, String> itemMap = new HashMap<>();
                        for (Cell c : h) {
                            //列
                            String name = Util.null2String(c.getName());
                            log.debug("RevokeLeaveAction key : {}, value : {}",c.getName(), c.getValue());
                            if ("cxsm".equals(name)) {
                                itemMap.put("cxsm", Util.null2String(c.getValue()));
                            }
                            if ("cxlyid".equals(name)) {
                                itemMap.put("cxlyid", Util.null2String(c.getValue()));
                            }
                            if ("cx".equals(name)) {
                                itemMap.put("cx", Util.null2String(c.getValue()));
                            }
                            if ("ksrq".equals(name)) {
                                itemMap.put("ksrq", Util.null2String(c.getValue()));
                            }
                            if ("jsrq".equals(name)) {
                                itemMap.put("jsrq", Util.null2String(c.getValue()));
                            }
                        }
                        log.debug("RevokeEliminationsAskForLeaveAction itemMap : [{}]",itemMap);
                        if (Util.null2String(itemMap.get("cx")).equals("1")) {
                            updateList.add(itemMap);

                            dateList = DateUtil.getDatesBetween(itemMap.get("ksrq"), "".equals(Util.null2String(itemMap.get("jsrq"))) ? itemMap.get("ksrq") : itemMap.get("jsrq"));
                            for (String date : dateList) {
                                //收集需要更改出勤结果数据状态的人员、日期信息
                                empDateItem = new HashMap<>();
                                empDateItem.put("empId", xjr);
                                empDateItem.put("cqDate", date);
                                empDateList.add(empDateItem);
                            }
                        }
                    }
                }
            }
            log.debug("RevokeLeaveAction updateList : [{}]",updateList);
            if (updateList.size() > 0) {
                updateList.forEach(f -> {
                    if (StringUtils.isNotBlank(f.get("cxlyid"))) {
                        String sql = "update uf_jcl_kq_qjjl_dt1" +" set "+"cxly=0,cxqj=1,cxsm=?,cxid=? where id = ?";
                        log.debug("RevokeEliminationsAskForLeaveAction sql : [{}]",sql);
                        DbTools.update(sql, Util.null2String(f.get("cxsm")), requestid, f.get("cxlyid"));
                        log.debug("RevokeEliminationsAskForLeaveAction cxsm : {}, requestid : {}, cxlyid : {}",Util.null2String(f.get("cxsm")), requestid, f.get("cxlyid"));
                        updateHoliday(f.get("cxlyid"),holidayItem.get("hsdw").toString());
                    }
                });

                //更新出勤结果中的数据状态
                String sjztUpdateResult = CommonUtil.updateAttendanceResultInfoStatus(empDateList, "0");
                if (!"".equals(sjztUpdateResult)) {
                    log.error("更新出勤结果中的数据状态失败:" + sjztUpdateResult);
                    requestInfo.getRequestManager().setMessageid("11111" + requestInfo.getRequestid() + "22222");
                    requestInfo.getRequestManager().setMessagecontent("更新出勤结果中的数据状态失败:" + sjztUpdateResult);
                    return Action.FAILURE_AND_CONTINUE;
                }
            }

        } catch (Exception e) {
            log.debug("流程数据报错:RevokeLeaveAction:");
            StringWriter errorsWriter = new StringWriter();
            e.printStackTrace(new PrintWriter(errorsWriter));
            log.debug(errorsWriter.toString());
            requestInfo.getRequestManager().setMessageid("11111" + requestInfo.getRequestid() + "22222");
            requestInfo.getRequestManager().setMessagecontent("【更改请假撤销状态action】报错，请联系管理员！");
            return Action.FAILURE_AND_CONTINUE;
        }

        return SUCCESS;


    }

    /**
     * 更新假期余额
     * @param dt1Id
     * @param hsdw
     */
    public void updateHoliday(String dt1Id,String hsdw){
        String sql = "select a.glmxid,a.jqye,sysc,b.qjsc,b.qtj,b.btj from uf_jcl_kq_qjjl_dt2 a left join uf_jcl_kq_qjjl_dt1 b on a.mainid=b.mainid and a.glmxid=b.glmxid  where b.id=?";
        List<Map<String,Object>> dataList = DbTools.getSqlToList(sql,dt1Id);
        log.debug("updateHoliday dataList :[{}]",dataList);
        Map<String,List<Map<String,Object>>> datagroupbyId = dataList.stream().collect(Collectors.groupingBy(e->e.get("jqye").toString()));
        for(Map.Entry<String,List<Map<String,Object>>> entry: datagroupbyId.entrySet()){
            String jqyeId = entry.getKey();
            List<Map<String,Object>> list = entry.getValue();
            double qjscTotal = list.stream().mapToDouble(e->Double.valueOf(e.get("qjsc").toString())).sum();
            double qtjTotal = list.stream().mapToDouble(e->Double.valueOf(e.get("qtj").toString())).sum();
            double btjTotal = list.stream().mapToDouble(e->Double.valueOf(e.get("qtj").toString())).sum();
            double qjsc = 0;

            if (AccountingUnitEnum.DAY.getKey().equals(hsdw)){
                qjsc = qtjTotal+btjTotal;
            }else if (AccountingUnitEnum.HOUR.getKey().equals(hsdw)){
                qjsc = qjscTotal + (qtjTotal+btjTotal)*8;
            }
            sql = "update uf_jcl_kq_jqye set yxsc=yxsc-"+qjsc+",wxsc=wxsc+"+qjsc+" where id=?";
            log.debug("updateHoliday sql : [{}]",sql);
            DbTools.update(sql,jqyeId);
        }

    }
}
